package services

import (
	"crypto/sha1"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"sort"
	"xwWechatPublic/middleware/app"
	"xwWechatPublic/utils/logging"
	"xwWechatPublic/utils/setting"
)

//微信支付回调
//type WxGetServerReq struct {
//	ToUserName		string 	`xml:"signature"`
//	FromUserName	string 	`xml:"echostr"`
//	CreateTime		int64 	`xml:"timestamp"`
//	MsgType			string 	`xml:"MsgType"`
//	Content			string	`xml:"Content"`
//	MsgId 			int64	`xml:"MsgId"`
//}

func str2sha1(data string) string {
	t := sha1.New()
	io.WriteString(t, data)
	return fmt.Sprintf("%x", t.Sum(nil))
}

//接收微信验证
func GetCheckServer(c *gin.Context) {
	appG := app.Gin{C: c}

	logging.Info("GetCheckServer ...")

	echostr := c.Query("echostr")
	logging.Info("echostr[%v]", echostr)

	token := setting.WechatSetting.Token
	signature := c.Query("signature")
	timestamp := c.Query("timestamp")
	nonce := c.Query("nonce")

	tmps := []string{token, timestamp, nonce}
	sort.Strings(tmps)

	//appG.ResponseSuccess()
	//appG.ResponseMessage(map[string]interface{}{
	//	"echostr": echostr,
	//})
	tmpStr := tmps[0] + tmps[1] + tmps[2]
	tmp := str2sha1(tmpStr)
	if tmp == signature {
		//fmt.Fprintf(w,echostr)
		logging.Info("回复微信消息")
		appG.C.Writer.WriteString(echostr)
	} else {
		//appG.ResponseSuccess()
		appG.ResponseXmlSuccess()
	}
}
